package com.kx.smartdevice.interceptors;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * @ClassName WebSocketInterceptor
 * @Author Sun
 * @Date 2021/6/2 18:49
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    /**
     * 握手之前，对数据进行处理，拿到设备的唯一标识，我们规定uri最后一位就是设备的uuid
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //获取到设备的唯一表示,保存到attributes
        String uri = request.getURI().toString();
        String uuid = uri.substring(uri.lastIndexOf("/")+1);
        attributes.put("uuid", uuid);
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }
}
